package simultaneously.pattern.producer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * 生产者消费者模式 concurrent.BlockingQueue实现
 */
class Producer implements Runnable{
    private final BlockingQueue<Integer> sharedQueue;
    public Producer(BlockingQueue<Integer> sharedQueue){
        this.sharedQueue = sharedQueue;
    }

    public void run(){
        for(int i=0;i<10;i++){
            try {
                System.out.println("produce:"+i);
                sharedQueue.put(i);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

class Customer implements Runnable{
    private final BlockingQueue<Integer> sharedQueue;
    public Customer(BlockingQueue<Integer> sharedQueue){
        this.sharedQueue = sharedQueue;
    }

    public void run(){
        while(true){
            try {
                System.out.println("custom:"+sharedQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ProducerCustomerPattern {
    public static void main(String[] args){
        BlockingQueue<Integer> queue = new LinkedBlockingDeque<Integer>();
        Thread proThread = new Thread(new Producer(queue));
        Thread cusThread = new Thread(new Customer(queue));
        proThread.start();
        cusThread.start();
    }
}
